package structure

import (
	"errors"
	"gitcode.com/G-YT/iHealth25/server/global"
	"gitcode.com/G-YT/iHealth25/server/model/common/request"
	"gitcode.com/G-YT/iHealth25/server/model/structure"
	structureReq "gitcode.com/G-YT/iHealth25/server/model/structure/request"
	"gitcode.com/G-YT/iHealth25/server/model/user"
	"gorm.io/gorm"
	"strconv"
	"strings"
)

type ServiceStationArticleService struct {
}

// CreateServiceStationArticle 创建服务站文章记录
// Author [piexlmax](https://github.com/piexlmax)
func (serviceStationArticleService *ServiceStationArticleService) CreateServiceStationArticle(serviceStationArticle *structure.ServiceStationArticle) (err error) {
	err = global.GVA_DB.Create(serviceStationArticle).Error
	return err
}

// DeleteServiceStationArticle 删除服务站文章记录
// Author [piexlmax](https://github.com/piexlmax)
func (serviceStationArticleService *ServiceStationArticleService) DeleteServiceStationArticle(serviceStationArticle structure.ServiceStationArticle) (err error) {
	err = global.GVA_DB.Delete(&serviceStationArticle).Error
	return err
}

// DeleteServiceStationArticleByIds 批量删除服务站文章记录
// Author [piexlmax](https://github.com/piexlmax)
func (serviceStationArticleService *ServiceStationArticleService) DeleteServiceStationArticleByIds(ids request.IdsReq) (err error) {
	err = global.GVA_DB.Delete(&[]structure.ServiceStationArticle{}, "id in ?", ids.Ids).Error
	return err
}

// UpdateServiceStationArticle 更新服务站文章记录
// Author [piexlmax](https://github.com/piexlmax)
func (serviceStationArticleService *ServiceStationArticleService) UpdateServiceStationArticle(serviceStationArticle structure.ServiceStationArticle) (err error) {
	err = global.GVA_DB.Save(&serviceStationArticle).Error
	return err
}

// GetServiceStationArticle 根据id获取服务站文章记录
// Author [piexlmax](https://github.com/piexlmax)
func (serviceStationArticleService *ServiceStationArticleService) GetServiceStationArticle(id uint) (serviceStationArticle structure.ServiceStationArticle, err error) {
	err = global.GVA_DB.Where("id = ?", id).Preload("ServiceStation").First(&serviceStationArticle).Error
	return
}

// GetServiceStationArticleInfoList 分页获取服务站文章记录
// Author [piexlmax](https://github.com/piexlmax)
func (serviceStationArticleService *ServiceStationArticleService) GetServiceStationArticleInfoList(info structureReq.ServiceStationArticleSearch) (list []structure.ServiceStationArticle, total int64, err error) {
	limit := info.PageSize
	offset := info.PageSize * (info.Page - 1)
	// 创建db
	db := global.GVA_DB.Model(&structure.ServiceStationArticle{}).Preload("ServiceStation")
	var serviceStationArticles []structure.ServiceStationArticle
	// 如果有条件搜索 下方会自动创建搜索语句
	if info.StartCreatedAt != nil && info.EndCreatedAt != nil {
		db = db.Where("created_at BETWEEN ? AND ?", info.StartCreatedAt, info.EndCreatedAt)
	}
	if info.Title != "" {
		db = db.Where("title LIKE ?", "%"+info.Title+"%")
	}
	if info.Status != 0 {
		db = db.Where("status = ?", info.Status)
	}
	err = db.Count(&total).Error
	if err != nil {
		return
	}

	if limit != 0 {
		db = db.Limit(limit).Offset(offset)
	}

	err = db.Find(&serviceStationArticles).Error
	return serviceStationArticles, total, err
}

// GetArticleList 获取服务站文章列表
// Author [g-qs](https://gitee.com/g-qs)
func (serviceStationArticleService *ServiceStationArticleService) GetArticleList(info structureReq.ServiceStationArticleSearch) (list []structure.ServiceStationArticle, total int64, err error) {
	limit := info.PageSize
	offset := info.PageSize * (info.Page - 1)
	// 创建db
	db := global.GVA_DB.Model(&structure.ServiceStationArticle{}).Preload("ServiceStation").Where("sc_id = ?", info.ScId)
	var serviceStationArticles []structure.ServiceStationArticle
	// 如果有条件搜索 下方会自动创建搜索语句
	if info.StartCreatedAt != nil && info.EndCreatedAt != nil {
		db = db.Where("created_at BETWEEN ? AND ?", info.StartCreatedAt, info.EndCreatedAt)
	}
	if info.Title != "" {
		db = db.Where("title LIKE ?", "%"+info.Title+"%")
	}
	if info.Status != 0 {
		db = db.Where("status = ?", info.Status)
	}
	err = db.Count(&total).Error
	if err != nil {
		return
	}

	if limit != 0 {
		db = db.Limit(limit).Offset(offset)
	}

	err = db.Find(&serviceStationArticles).Error
	return serviceStationArticles, total, err
}

// GetArticleById 根据ID获取服务站文章
// Author [g-qs](https://github.com/g-qs)
func (serviceStationArticleService *ServiceStationArticleService) GetArticleById(id uint, userID uint) (article structure.ServiceStationArticle, err error) {
	err = global.GVA_DB.Transaction(func(tx *gorm.DB) error {
		if err = tx.Where("id = ?", id).First(&article).Error; err != nil {
			return errors.New("文章不存在")
		}
		// 检查当前用户是否已存在于ReadList中
		if article.ReadList == "" {
			// 如果无人阅读过
			article.ReadList = strconv.FormatUint(uint64(userID), 10)
		} else if !containsUserID(article.ReadList, userID) {
			// 如果不存在，添加到ReadList中
			article.ReadList += "," + strconv.FormatUint(uint64(userID), 10)
		}
		// 增加浏览量
		article.Pv++
		// 更新数据库中的文章信息
		if err = tx.Model(&structure.ServiceStationArticle{}).Where("id = ?", id).Updates(structure.ServiceStationArticle{Pv: article.Pv, ReadList: article.ReadList}).Error; err != nil {
			return errors.New("更新浏览量失败")
		}
		return nil
	})
	return
}

// GetReadList 获取文章阅读名单
// Author [g-qs](https://gitee.com/g-qs)
func (serviceStationArticleService *ServiceStationArticleService) GetReadList(id uint) (userList []user.User, err error) {
	var serviceStationArticle structure.ServiceStationArticle
	err = global.GVA_DB.Where("id = ?", id).First(&serviceStationArticle).Error
	userIDList := strings.Split(serviceStationArticle.ReadList, ",")
	if err = global.GVA_DB.Where("id IN (?)", userIDList).Find(&userList).Error; err != nil {
		return nil, errors.New("获取阅读列表失败")
	}
	return
}

// containsUserID 检查用户ID是否存在于阅读名单中
func containsUserID(readList string, userID uint) bool {
	if readList == "" {
		return false
	}
	userIDstr := strconv.FormatUint(uint64(userID), 10)
	// 简单的字符串匹配，你可能需要更复杂的逻辑来处理
	return contains(strings.Split(readList, ","), userIDstr)
}

// contains 检查元素是否存在于切片中
func contains(slice []string, element string) bool {
	for _, v := range slice {
		if v == element {
			return true
		}
	}
	return false
}
